﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml;
using System.Text;
using System.Data;
using System.Collections;
using System.Configuration;

namespace Rainy.FrameWork
{
    /// <summary>
    /// 文件操作
    /// </summary>
    public class FileOperation
    {
        public static string filePath = WebConfig.SystemFilePath + "Movies\\";//文件的存放路径(本地)
        public static string tempPath = WebConfig.SystemFilePath + "Movies\\UploadTemp";//临时文件的存放路径(本地)

        #region <--老文件的删除-->
        /// <summary>
        /// 老文件的删除，以天为单位来算.如过了相应的时间会把以前的记录全部删除掉.
        /// 默认删除1天以前的文件
        /// </summary>
        public void DelOldAnnexFile()
        {
            string[] tempFileNames = Directory.GetFiles(tempPath);
            try
            {
                foreach (string tempFile in tempFileNames)
                {
                    if (DateTime.Compare(File.GetCreationTime(tempFile).AddDays(1), DateTime.Now) < 0)
                    {
                        //判断文件是否存在,存在删除,否则继续循环
                        if (File.Exists(tempFile))
                        {
                            //文件删除
                            File.Delete(tempFile);
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }
        #endregion

        #region <--获取可上传的文件类型-->
        /// <summary>
        /// 获取可上传的文件类型
        /// </summary>
        /// <param name="code">配置文件中的Code值:01:高校评估附件上传;02:资料附件上传</param>
        /// <param name="extensionName">扩展名(不带.)</param>
        /// <returns>true:允许;false:不允许</returns>
        public bool GetUploadFileType(string code, string extensionName)
        {
            bool returnValue = false;
            string xmlPath = WebConfig.SystemXmlPath +"Business/ExtensionType.xml";
            //检测配置文件是否存在,存在加载文件并处理
            if (File.Exists(xmlPath))
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(xmlPath);
                XmlNode root = xmldoc.DocumentElement;
                if (root != null)
                {
                    XmlNode node = xmldoc.DocumentElement.SelectSingleNode("//ExtensionTypes[@Code='" + code + "']/ExtensionType[@Type='" + extensionName + "']");
                    if (node != null)
                    {
                        returnValue = true;
                    }
                }

            }
            return returnValue;
        }
        #endregion

        #region <--上传评估文件操作-->
        /// <summary>
        /// 上传评估文件操作
        /// </summary>
        /// <param name="annexType">1:高校评估附件上传;2:资料附件上传</param>
        /// <returns>true:成功;false:失败</returns>
        public bool UploadAssessFile(string attachmentID, string saveUrl, string assessReportID, string fileName, string attachmentCacheKey, string logName, string userName)
        {
            bool returnValue = false;
            this.Message = string.Empty;
            DataOperation dataOperation = new DataOperation();

            //2.保存信息到:附件信息信息（Attachment）表
            FieldData dataFields = new FieldData();
            dataFields.Add("AttachmentID", attachmentID);
            dataFields.Add("ReportID", assessReportID);
            dataFields.Add("AnnexName", fileName);
            dataFields.Add("AnnexInfo", saveUrl.Replace(@"\", "/"));

            dataFields.Add("CreatePersonAccount", logName);
            dataFields.Add("CreatePersonName", userName);
            dataFields.Add("CreateTime", DateTime.Now);
            try
            {
                //1.老文件删除
                this.DelOldAnnexFile();
                DataTable dt = dataOperation.AddUpdateCacheData(Tables.TestTable, dataFields, attachmentCacheKey);

                if (dt != null)
                {
                    returnValue = true;
                }
            }
            catch (Exception exp)
            {
                this.Message = exp.Message;
            }
            return returnValue;
        }
 
        #endregion

        #region <--文件拷贝删除(临时文件到正式文件夹)
        /// <summary>
        /// 文件拷贝删除
        /// </summary>
        /// <param name="AttachmentCacheKey">缓存键名</param>
        /// <param name="dbFilePath">正式文件路径(不包括扩展名)</param>
        public void CopyAndDelFile(string AttachmentCacheKey, string dbFilePath)
        {
            //判断正式文件夹是否存在,不存在创建
            if (!Directory.Exists(filePath + dbFilePath))
            {
                Directory.CreateDirectory(filePath + dbFilePath);
            }
            string[,] cacheArry = this.AddListCache(AttachmentCacheKey);
            //文件拷贝且删除临时文件(临时文件夹到正式文件夹)
            int iLen = cacheArry.Length / cacheArry.Rank;
            if (iLen > 0)
            {
                for (int i = 0; i < iLen; i++)
                {
                    //缓存中的访问路径
                    string cacheAnnexInfo = cacheArry[i, 0].Replace("/", @"\");
                    //缓存中的文件名称(不含路径)
                    string cacheFileName = cacheAnnexInfo;
                    if (cacheAnnexInfo.LastIndexOf(@"\") != -1)
                    {
                        cacheFileName = cacheAnnexInfo.Substring(cacheAnnexInfo.LastIndexOf(@"\"));
                    }
                    //正式文件所在本地路径(含文件名及扩展名)
                    string destFileName = filePath + dbFilePath + cacheFileName;
                    //临时文件所在本地路径(含文件名及扩展名)
                    string sourceFileName = tempPath + cacheFileName;
                    //判断是删除还是新增
                    if (cacheArry[i, 1] == "01")//新增或修改
                    {
                        //文件拷贝
                        if (File.Exists(sourceFileName))
                        {
                            System.IO.File.Copy(sourceFileName, destFileName);
                            //临时文件删除
                            System.IO.File.Delete(sourceFileName);
                        }
                    }
                    else if (cacheArry[i, 1] == "02")//删除
                    {
                        //临时文件或正式文件删除
                        if (File.Exists(sourceFileName))//临时文件删除
                        {
                            System.IO.File.Delete(sourceFileName);
                        }
                        if (File.Exists(destFileName))//正式文件删除
                        {
                            System.IO.File.Delete(destFileName);
                        }
                    }
                }
            }
        }
        #endregion


        public string[,] AddListCache(string AttachmentCacheKey)
        {
            DataOperation dataOperation = new DataOperation();
            Dictionary<Hashtable, TableInfo> attachmentDictionary = dataOperation.GetCacheDatas(AttachmentCacheKey, Tables.TestTable);
            //将附件信息一条条放到数据字典中
            string[,] cacheArry = new string[attachmentDictionary.Count, 2];//用于存放新增或删除的附件数据
            int i = 0;
            foreach (KeyValuePair<Hashtable, TableInfo> item in attachmentDictionary)
            {
                //获取附件信息,以便将临时文件夹文件拷贝到相应目录
                Hashtable ht = item.Key;
                string annexInfo = string.Empty;
                foreach (DictionaryEntry str in ht)
                {
                    //判断是否是要物理删除的数据，如果是，则记录为01，否则记录为02
                    if (ht.Count == 1 && ht.Contains(item.Value.PrimaryName))//删除
                    {
                        //从缓存中获取主键值
                        DataView dv = dataOperation.GetCacheData(AttachmentCacheKey);
                        if (dv != null)
                        {
                            DataRow[] drs = dv.Table.Select(item.Value.PrimaryName + "='" + str.Value.ToString() + "'");
                            annexInfo = drs[0]["ANNEXINFO"].ToString();
                        }
                        cacheArry[i, 0] = annexInfo;
                        cacheArry[i++, 1] = "02";
                        break;
                    }
                    else
                    {
                        if (str.Key.ToString().ToUpper() == "ANNEXINFO")
                        {
                            annexInfo = str.Value.ToString();
                            cacheArry[i, 0] = annexInfo;
                            cacheArry[i++, 1] = "01";
                            break;
                        }
                    }
                }
            }
            return cacheArry;
        }

        #region <--保存时修改内存中的数据-->
        /// <summary>
        /// 保存时修改内存中的数据
        /// </summary>
        /// <param name="dbFilePath">数据库中保存的路径(不含文件名)</param>
        /// <param name="AttachmentCacheKey">缓存键名</param>
        public void ModifyCacheData(string dbFilePath,string AttachmentCacheKey)
        {
            DataTable subTable = (DataTable)System.Web.HttpContext.Current.Cache[AttachmentCacheKey];
            foreach (DataRow drow in subTable.Rows)
            {
                 //删除时,无需处理访问路径的问题
                if (drow.RowState != DataRowState.Deleted)//删除
                {
                    string annexInfoold = drow["ANNEXINFO"].ToString().Replace("\\", "/");
                    if (annexInfoold.IndexOf("/") == -1)
                    {
                        drow["ANNEXINFO"] = dbFilePath.Replace("\\", "/") + annexInfoold;
                    }
                }
            }
        }
        #endregion

        #region <--获取正式保存的路径-->
        /// <summary>
        /// 获取正式保存的路径
        /// </summary>
        /// <param name="movid">视频记录编号</param>
        /// <returns></returns>
        public string GetSaveFilePath(string movid)
        {
            string dbFilePath = string.Empty;

            dbFilePath = System.DateTime.Now.ToString("yyyy-MM") + "\\" + movid + "\\";
            string savePath = filePath + dbFilePath;
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            return dbFilePath;
        }
        #endregion

        private string message = string.Empty;
        public string Message
        {
            get;
            set;
        }
    }
}
